package com.wy.cms.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wy.cms.constant.CmsRedisConst;
import com.wy.cms.constant.CookieNameConst;
import com.wy.common.BaseCommonController;
import com.wy.constant.CookieConst;
import com.wy.dto.cms.CmsUserDto;
import com.wy.service.ex.ICmsUserExService;
import com.wy.util.CookieUtil;
import com.wy.util.EncryptUtil;
import com.wy.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

public class BaseController extends BaseCommonController {

	@Autowired
	private ICmsUserExService cmsUserExService;

	protected CmsUserDto getCmsUserDto() throws Exception {
		Long id = getCookieValueByUserId();
		String key = CmsRedisConst.USER_KEY + id;
		CmsUserDto cmsUserDto  = null;
		if(!RedisUtil.getInstance().exists(key)){
			cmsUserDto = cmsUserExService.findCmsUserDtoById(id);
			if(null!=cmsUserDto){
				RedisUtil.getInstance().set(key, JSON.toJSONString(cmsUserDto), 5L, TimeUnit.HOURS);
			}
		} else {
			cmsUserDto = JSON.parseObject(RedisUtil.getInstance().get(key).toString(),CmsUserDto.class);
		}
		return cmsUserDto;
	}

	protected void setCmsUserDto(CmsUserDto cmsUserDto) throws Exception {
		if(null!=cmsUserDto){
			String key = CmsRedisConst.USER_KEY + cmsUserDto.getId();
			RedisUtil.getInstance().set(key, JSON.toJSONString(cmsUserDto));
		}
	}

	protected String getCookieValue() throws Exception{
		return EncryptUtil.decode(CookieUtil.getCookieValue(request.getCookies(), CookieConst.WY_CMS_COOKIE_NAME));
	}

	protected Long getCookieValueByRoleId() throws Exception{
		String cookieValue  = getCookieValue();
		JSONObject object = JSON.parseObject(cookieValue);
		return object.getLong(CookieNameConst.CMS_ROLE_ID);
	}

	protected Long getCookieValueByUserId() throws Exception{
		String cookieValue  = getCookieValue();
		JSONObject object = JSON.parseObject(cookieValue);
		return object.getLong(CookieNameConst.CMS_USER_ID);
	}

}